package com.ygqh.baby.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.model.SchJob;
import com.ygqh.baby.po.ScheduleJob;
import com.ygqh.baby.quartz.QuartzManager;
import com.ygqh.baby.quartz.ScheduleJobApi;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/job")
public class QuartzController extends BaseController<Object, java.lang.Long> {

    @Autowired
    private ScheduleJobApi scheduleJobApi;

    @RequestMapping(value = "jobRoute", method = RequestMethod.POST)
    @ResponseBody
    public Message jobRoute(String method, String job, HttpServletRequest request) throws SchedulerException {
        if (StringUtils.isEmpty(method)) {
            return Message.error("方法名不能为空", null);
        }
        if (StringUtils.isEmpty(job)) {
            return Message.error("job不能为空", null);
        }
        ScheduleJob scheduleJob = JSON.parseObject(job, new TypeReference<ScheduleJob>() {
        });
        System.out.println(DateConvertUtils.formatDateTime(scheduleJob.getCronDate()));
        Message msg;
        if (method.equals("addJob")) {
            msg = scheduleJobApi.addJob(scheduleJob);
        } else if (method.equals("updateJobCron")) {
            msg = scheduleJobApi.updateJobCron(scheduleJob);
        } else if (method.equals("delJob")) {
            msg = scheduleJobApi.deleteJob(scheduleJob);
        } else if (method.equals("getAllJob")) {
            msg = getAllJob(scheduleJob.getJobGroup(), scheduleJob.getJobName());
        } else {
            msg = Message.error("方法明不存在", method);
        }
        return msg;
    }

    @RequestMapping(value = "/getRunningJob")
    @ResponseBody
    public Message getRunningJob() throws SchedulerException {

        List<SchJob> runningJob = QuartzManager.getRunningJob();
        return Message.success(runningJob);
    }

    @RequestMapping(value = "/getAllJob")
    @ResponseBody
    public Message getAllJob(String groupName, String jobName) throws SchedulerException {

        List<ScheduleJob> runningJob = QuartzManager.getAllJob(groupName, jobName);
        return Message.success(runningJob);
    }

    @RequestMapping(value = "/getJobByJobName")
    @ResponseBody
    public Message getJobByJobName(String jobName, String jobGroup) throws SchedulerException {
        SchJob job = QuartzManager.getJobByJobName(jobName, jobGroup);
        return Message.success(job);
    }

}
